package com.dogkr.server.web;

import java.util.Date;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.dogkr.common.ServerAction;
import com.dogkr.server.entity.User;
import com.dogkr.server.entity.UserMessage;
import com.dogkr.server.entity.UserMessage.MsgType;
import com.dogkr.server.service.MessageService;
import com.dogkr.server.service.UserService;
import com.sean.common.page.Pagination;
import com.sean.common.page.ResultPagination;


// 设置Struts2注解
@ParentPackage(value = "login-default")
@Namespace(value = "/msg")
@ResultPath("/WEB-INF/jsps")
// 页面文件空间
@Results({
	@Result(name = "create", location = "win_create.jsp"),
	@Result(name = "show", location = "show.jsp")
})
public class MessageAction extends ServerAction {
	private static final long serialVersionUID = 1L;
	
	private UserMessage msg;
	
	@Autowired
	private MessageService messageService;
	
	@Action(value = "list")
	public void listData() {
		Pagination pagination = this.getPaginationForParameter();
		ResultPagination<UserMessage> res = messageService.selectMessage(this.getLoginUser().getId(), pagination);
		outJson(res);
	}
	
	@Action(value = "show")
	public String show() {
		UserMessage msg = messageService.selectMessageById(this.getLoginUser().getId(), id);
		put("msg", msg);
		return "show";
	}
	
	@Action(value = "create")
	public String create() {
		if(id != null) {
			UserMessage msg = messageService.selectMessageById(this.getLoginUser().getId(), id);
			put("msg", msg);
		}
		return "create";
	}
	
	
	@Action(value = "add")
	public void add() {
		User user = this.getLoginUser();
		if(msg != null) {
			msg.setInsert(user);
			msg.setMsgType(MsgType.MSG.getVal());
			messageService.insertMessage(msg, id);
		} else {
			res = this.getErrRes();
		}
		outJson(res);
	}
	
	@Action(value = "unread")
	public void checkUnread() {
		User user = this.getLoginUser();
		Date last = (Date) this.getSessiont().getAttribute("LAST_CHECK_UNREAD");
		if(last == null || last.getTime() < ((new Date()).getTime() - 1000*1)) {
			out(new Integer(messageService.checkUnreadMessage(user.getId())).toString());
			this.getSessiont().setAttribute("LAST_CHECK_UNREAD", new Date());
		}
	}

	public UserMessage getMsg() {
		return msg;
	}

	public void setMsg(UserMessage msg) {
		this.msg = msg;
	}
}
